#!/bin/bash
#关闭防火墙/selinux
files="/root/IP.txt"   #存放IP地址
files_port="/root/redis_prot.txt"  #存放port号
redis_ipandport="/root/all.txt"    #集群的IP与端口号
Shell_path="`pwd`"/"$0"
Shell_name=$0
function Firewall_Selinx(){
        systemctl status firewalld  |grep  running   &&   systemctl stop  firewalld; systemctl disable firewalld
        selinux=$(getenforce)
        if [  "$selinux" = "Permissive" -o   "$selinux"  = "Enforcing" ];then
                #临时关闭selinux
                setenforce   0
                #永久关闭selinux
                cat  /etc/sysconfig/selinux   |grep  disabled  |grep  -v "^#"
                if  [ $? -eq 0 ];then
                        echo  “已经永久关闭selinux”
                else
                         sed   -i  "7{s/^SELINUX.*/SELINUX=disabled/g}"

                fi
        else
                echo "selinux模式关闭"
        fi
}

function   SSH_OK(){
        [ -f $files ] || touch $files
        echo " "  >  $files
        if [ ! -f ~/.ssh/id_rsa.pub ];then
                ssh-keygen -t rsa  -P ""  -f ~/.ssh/id_rsa
        fi
        Network_card=`ifconfig  |egrep  "^e" |head -n 1 |awk   -F ":" '{print $1}'|head  -n 1`
        Network_segment=`ifconfig  $Network_card |awk '/broadcast/{print $2}' | awk -F '.'  '{print $1"."$2"."$3}'`
        echo "你的网段为:$Network_segment"
        #只适用于同网段
	#echo  -e "\033[34m只需要输入IP地址的最后一位就可以\033[0m" 
        #read -p  "开始范围：" Start
        #read -p  "结束范围：" End
	Start="1"
	End="254"
        for  IP_Address  in  `seq $Start $End`
        do
               (ping -c 3 "$Network_segment".$IP_Address > /dev/null
                if [ $? -eq 0 ];then
                                echo  "$Network_segment".$IP_Address  >>  $files
                fi)&
        done
        wait
        More_IP_Addresses=`cat $files |xargs`
        for  Single_IP_Address in  ${More_IP_Addresses[@]}
        do
#下面的非交互有个缺点，单一性下面的密码全部都是一致
/usr/bin/expect <<-EOF
spawn ssh-copy-id    root@$Single_IP_Address
expect {
  "yes/no"  {send "yes\n";exp_continue}
  "password"  {send "root\n"}
}
expect eof
EOF
	                ssh root@$Single_IP_Address  'echo |ssh-keygen -t rsa  -P ""  -f ~/.ssh/id_rsa'
                        scp   -r   $Single_IP_Address:/root/.ssh/id_rsa.pub    /root/.ssh/host
                        cat  /root/.ssh/host  >> /root/.ssh/authorized_keys
        done
        #将上线的主机公钥全部传给各个主机(双机互信功能，不需要只需要注释即可)
        for  Any_IP_address in ${More_IP_Addresses[@]}
        do
                scp -r /root/.ssh/authorized_keys   $Any_IP_address:/root/.ssh/authorized_keys
        done
}


function redis_conf(){
        wget --tries=3 http://download.redis.io/releases/redis-5.0.5.tar.gz
        tar  -zxf redis-5.0.5.tar.gz  -C   /usr/local/
        cd /usr/local/redis-5.0.5
        make  MALLOC=libc
        make install PREFIX=/usr/local/redis
	#根据端口号进行创建对应目录ID
	[ -f $files_port ]  || touch $files_port
	echo  "" > $files_port
	#read  -p  "输入需要开启redis端口" -a  redis_ports
	#echo  "${redis_ports}"
	redis_ports="7000 7001"
	#进行判断。让用户再次确定进行集群调试（待优化）
	for  redis_Catalog in ${redis_ports[@]}
	do	
		echo  "$redis_Catalog"  >>  $files_port
		Catalog="/usr/local/redis-cluster/$redis_Catalog"
		[ -d ${Catalog} ] &&  echo  "目录存在" || mkdir -p $Catalog
		cp  -ar   /usr/local/redis/bin/*   $Catalog
		#获取本机IP
		wangke=`ifconfig  |egrep  "^e" |head -n 1 |awk   -F ":" '{print $1}'|head  -n 1`  #获取网卡名称
		Network=`ifconfig  $wangke |awk '/broadcast/{print $2}'`   
		echo "port $redis_Catalog
		bind  $Network
		cluster-enabled yes
		cluster-config-file nodes.conf
		cluster-node-timeout 5000
		appendonly yes
		daemonize yes
		protected-mode no
		pidfile /usr/local/redis-cluster/$redis_Catalog/$redis_Catalog.pid" >  /usr/local/redis-cluster/$redis_Catalog/redis.conf
		sed -i 's/^[ \t]*//' /usr/local/redis-cluster/$redis_Catalog/redis.conf  #去除首行空格
		sleep  0.5s
	done
}

function redis_conf_single(){
        wget --tries=3 http://download.redis.io/releases/redis-5.0.5.tar.gz
        tar  -zxf redis-5.0.5.tar.gz  -C   /usr/local/
        cd /usr/local/redis-5.0.5
        make  MALLOC=libc
        make install PREFIX=/usr/local/redis
        #根据端口号进行创建对应目录ID
        [ -f $files_port ]  || touch $files_port
        echo  "" > $files_port
        redis_ports="7000 7001 7002  7003  7004  7005"
        #进行判断。让用户再次确定进行集群调试（待优化）
        for  redis_Catalog in ${redis_ports[@]}
        do
                echo  "$redis_Catalog"  >>  $files_port
                Catalog="/usr/local/redis-cluster/$redis_Catalog"
                [ -d ${Catalog} ] &&  echo  "目录存在" || mkdir -p $Catalog
                cp  -ar   /usr/local/redis/bin/*   $Catalog
                #获取本机IP
                wangke=`ifconfig  |egrep  "^e" |head -n 1 |awk   -F ":" '{print $1}'|head  -n 1`  #获取网卡名称
                Network=`ifconfig  $wangke |awk '/broadcast/{print $2}'`
                echo "port $redis_Catalog
                bind  $Network
                cluster-enabled yes
                cluster-config-file nodes.conf
                cluster-node-timeout 5000
                appendonly yes
                daemonize yes
                protected-mode no
                pidfile /usr/local/redis-cluster/$redis_Catalog/$redis_Catalog.pid" >  /usr/local/redis-cluster/$redis_Catalog/redis.conf
                sed -i 's/^[ \t]*//' /usr/local/redis-cluster/$redis_Catalog/redis.conf  #去除首行空格
                sleep  0.5s
        done
}

#redis启动服务
function  redis_start(){
	redis_confCatalog="/usr/local/redis-cluster"
	#将/usr/local/redis-cluster目录下创建出来的目录（端口）记录到一个文件
	ls $redis_confCatalog |grep  -v  [a-z]  >  Redis_Route.txt
	Route=`cat Redis_Route.txt |xargs`
	#根据获取到开放端口号依次去启动redis服务
	for  Routes in  ${Route[@]}
	do
		#进入redis目录启动redis服务
		cd /usr/local/redis-cluster/$Routes
		/usr/local/redis-cluster/$Routes/redis-server   /usr/local/redis-cluster/$Routes/redis.conf
		sleep 0.5s
		
		#查看端口是否有master和slave启动端口
		netstat  -tunlp|grep  "${Routes}" |grep -v  "1${Routes}"  &>/dev/null
		if [ $? -eq 0 ];then
			echo  "端口${Routes} redis服务启动成功"
		else
			echo   "端口${Routes} redis服务启动失败,检查端口${Routes} redis的配置文件"
		fi
	done
}

function redis_colony(){
	start_client="/usr/local/redis/bin/redis-cli"
	redis_needIP=`cat $files |xargs`
	redis_needprot=`cat $files_port |xargs`
	[ -f  $redis_ipandport ] || touch $redis_ipandport
	#主要是保证这个文件什么都没有。下追加方式写入到文件中
	echo  " " > $redis_ipandport
	for  redisip  in  ${redis_needIP[@]}
	do
		for  redisport  in  ${redis_needprot[@]}
		do
			#生成IP与端口，将其粘合在一起
			echo -n  "$redisip"":" >>  $redis_ipandport
			echo   "$redisport" >>   $redis_ipandport    
		done
	done
redis_all=`cat $redis_ipandport |xargs`
echo  $redis_all > $redis_ipandport
Redis_IpandPort=`cat $redis_ipandport`
echo Redis_IpandPort
/usr/bin/expect <<-EOF
spawn   $start_client --cluster create  $Redis_IpandPort  --cluster-replicas 1
expect {
	"Can I set the above configuratio" {send "yes\n"}
}
expect eof
EOF
echo  "连接测试/usr/local/redis/bin/redis-cli  -c  -p 7000  -h 主机IP"
}

function Dependency_packages(){
	Packages="gcc make curl wget expect"
	for   redis_needpackage  in  ${Packages[@]}
	do
		rpm -q $redis_needpackage  &&  echo  -e "\033[5;31m${redis_needpackage} 已经安装\033[0m" || yum  install  -y  $redis_needpackage 
	done
}


function Ending(){
	#删除多余的文件造成磁盘浪费
	rm  -rf  $files  $files_port  $redis_ipandport  /tmp/redis_new.sh
}

read -p  "你需要的测试环境
1):虚拟机
2):云服务
"  Choice_num
if [ "$Choice_num" = "1" ];then
	#1）先保证ssh登入到每个机器
	#判断单机还是多机
read -p  "你想部署redis单机还是多机器集群？
1) ————单机
2) ————多机" Redis_Single_Ro_Double
	if [ "$Redis_Single_Ro_Double" = "1" ];then
		Virtual_Machine_Single="Dependency_packages  redis_conf_single  redis_start redis_colony"
			for  virtual  in  ${Virtual_Machine_Single[@]}
		        do
         		      $virtual
		        done
			Ending
	elif [ "$Redis_Single_Ro_Double" = "2" ];then
		SSH_OK  #多机的话保证能够免密登入（前提）
		cat  /root/IP.txt
		read  -p  "搭建redsi集群是否如上主机?   y/n"   Redis_Monitoring_Room
		if [ "$Redis_Monitoring_Room" = "y"  -o "$Redis_Monitoring_Room" = "yes" ];then
			Redis_All_Hosts=`cat  $files |xargs`
				for  Redis_Hosts  in  ${Redis_All_Hosts[@]}
				do
					#因为传输脚本到目下不知到会不会有其他sh脚本，为了安全起见创建一个新的目录
					ssh  root@$Redis_Hosts   '[ -d /tmp/redis ] || /usr/bin/mkdir  /tmp/redis'
					scp  -r  $Shell_path  root@$Redis_Hosts:/tmp/redis
					#*是因为是保证了不管我们这个脚本名字为任何都可以保证一致，提高机动性
					ssh  root@$Redis_Hosts  'head  -n  206 /tmp/redis/*.sh | tail -n 206 > /tmp/redis/redis_new.sh'
					ssh  root@$Redis_Hosts 	'echo -e "Dependency_packages\nredis_conf\nredis_start\nredis_colony" >> /tmp/redis/redis_new.sh '
					ssh  root@$Redis_Hosts  'sh  /tmp/redis/redis_new.sh'
				done
				Ending
		else
			read -p  "那手动输入需要搭建redis集群的机器IP"  -a  redis_listenIP
				for listens in ${redis_listenIP[@]}
				do
					ssh root@$listens '[ -d /tmp/redis ] || /usr/bin/mkdir  /tmp/redis'
					scp  -r  $Shell_path root@$listens:/tmp/redis
					ssh  root@$listens   'head   -n  206  /tmp/redis/*.sh | tail -n 206  > /tmp/redis/redis_new.sh'
					ssh  root@$listens   'echo -e "Dependency_packages\nredis_conf\nredis_start\nredis_colony" >> /tmp/redis/redis_new.sh'
					ssh  root@$listens   'sh  /tmp/redis/redis_new.sh'
				done
				Ending
		fi
	else 
		echo "输入正确选择"
		
	fi
elif  [ "$Choice_num" = "2" ];then
	read -p  "你想部署redis单机还是多机器集群？
1) ————单机
2) ————多机" Cloud_Services_Single_Or_Double
	if [ "$Cloud_Services_Single_Or_Double" = "1" ];then
		Dependency_packages
                Baifdu_IP=`curl ip.cip.cc`   #获取公网IP
                echo  -e "\033[5;31m当前服务器公网IP为: $Baifdu_IP\033[0m"
		sleep 2s
                echo   -n  206  /tmp/redis/*.sh | tail -n 206  "${Baifdu_IP}"  > $files
                cat $files
                sleep  1s
                Cloud_services="redis_conf_single   redis_start redis_colony"
                for  Cloud  in  ${Cloud_services[@]}
                do
                        $Cloud
                done
		Ending
	elif [ "$Cloud_Services_Single_Or_Double" = "2" ];then
		echo  "目前还没想好"
		Ending
	else
		echo  "请选择正确的选择"
	fi
else
	echo  -e "\033[5;31m请输入正确的选项：1:虚拟机  2:云服务\033[0m"
fi
